package com.open.system.controller;

import com.open.common.controller.BaseController;
import com.open.common.utils.DateUtils;
import com.open.common.utils.PageUtils;
import com.open.common.utils.Query;
import com.open.common.utils.R;
import com.open.system.domain.*;
import com.open.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

//import com.open.loan.utils.sms.SmsTools;

/**
 * 申请认证
 */

@Controller
@RequestMapping("/system/loanApply")
public class LoanApplyController extends BaseController {
    @Autowired
    private LoanApplyService loanApplyService;

    @Autowired
    private LoanUserService loanUserService;

    @Autowired
    private LoanApplyLogService loanApplyLogService;

    @Autowired
    private LoanAdminLogService loanAdminLogService;

    @Autowired
    private LoanContactService loanContactService;

    @Autowired
    private LoanFaceService loanFaceService;

    @Autowired
    private LoanFaceLogService loanFaceLogService;

    @Autowired
    private LoanFileService loanFileService;

    @Autowired
    private LoanBankService loanBankService;

    @Autowired
    private LoanUserService userService;

    @Autowired
    private RepayLogService repayLogService;

    @GetMapping()
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply() {
        return "system/loanApply/loanApply";
    }

    @GetMapping("/apply1")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply1() {
        return "system/loanApply/loanApply1";
    }

    @GetMapping("/apply2")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply2() {
        return "system/loanApply/loanApply2";
    }

    @GetMapping("/apply3")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply3() {
        return "system/loanApply/loanApply3";
    }

    @GetMapping("/apply4")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply4() {
        return "system/loanApply/loanApply4";
    }

    @GetMapping("/selectPhone")
    @RequiresPermissions("system:loanApply:loanApply")
    String selectPhone() {
        return "system/loanApply/selectPhone";
    }

    @GetMapping("/apply5")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply5() {
        return "system/loanApply/loanApply5";
    }

    //已拒绝
    @GetMapping("/apply6")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply6() {
        return "system/loanApply/loanApply6";
    }

    //已还清
    @GetMapping("/apply7")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply7() {
        return "system/loanApply/loanApply7";
    }

    //操作几个状态--通过人脸通过审核和应用商通过审核
    @GetMapping("/apply8")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply8() {
        return "system/loanApply/loanApply8";
    }

    @GetMapping("/apply9")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanApply9() {
        return "system/loanApply/loanApply9";
    }

    @GetMapping("/loanClearApply")
    @RequiresPermissions("system:loanApply:loanApply")
    String LoanClearApply() {
        return "system/loanApply/loanClearApply";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("system:loanApply:loanApply")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //--操作日志--开始--
        String shopId = getUser().getEmail();
        String adminName = getUser().getName();
        String Module = "申请认证";
        String detail = "查看申请认证表";
        loanAdminLogService.saveLog(shopId, adminName, Module, detail);
        //--操作日志--结束--

        //查询列表数据
        if (shopId != null && shopId != "" && !"1".equals(shopId)) {
            params.put("remark7", shopId);
        }
        Query query = new Query(params);
        List<LoanApplyDO> loanApplyList = loanApplyService.list(query);
        for (int i = 0; i < loanApplyList.size(); i++) {
            LoanApplyDO applyDO = loanApplyList.get(i);
            applyDO.setHasShowSysName(shopId);
        }
        int total = loanApplyService.count(query);
        PageUtils pageUtils = new PageUtils(loanApplyList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("system:loanApply:add")
    public String add() {
        return "system/loanApply/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("system:loanApply:edit")
    public String edit(@PathVariable("id") Long id, Model model) {
        LoanApplyDO loanApply = loanApplyService.get(id);
        model.addAttribute("loanApply", loanApply);
        return "system/loanApply/edit";
    }


    @GetMapping("/repayInfo/{id}")
    @RequiresPermissions("system:loanApply:edit")
    public String details(@PathVariable("id") Long id, Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", id);
        List<LoanApplyDO> loanUsers = loanApplyService.list(map);
        LoanApplyDO loanApply = loanUsers.get(0);
        model.addAttribute("loanApply", loanApply);

        List<RepayLogDO> repays = repayLogService.list(map);
        model.addAttribute("repays", repays);
        if (repays != null && repays.size() > 0) {
            RepayLogDO repayInfo = repays.get(0);
            model.addAttribute("repayInfo", repayInfo);
        } else {
            RepayLogDO repayInfo = new RepayLogDO();
            model.addAttribute("repayInfo", repayInfo);
        }
        return "system/loanApply/repayInfo";
    }


    @GetMapping("/details/{id}")
    @RequiresPermissions("system:loanApply:details")
    String details(@PathVariable("id") Long id, Model model, HttpServletRequest request) {
        LoanApplyDO loanApply = loanApplyService.get(id);
        model.addAttribute("loanApply", loanApply);

        if ("1".equals(request.getParameter("downType"))) {
            return "system/loanApply/detailsDownLoad";
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", loanApply.getUserId());
        List<RepayLogDO> repays = repayLogService.list(map);
        model.addAttribute("repays", repays);
        return "system/loanApply/details";
    }


    @ResponseBody
    @PostMapping("/resetbill")
    @RequiresPermissions("system:loanApply:add")
    public R resetbill(LoanApplyDO loanApply) throws Exception {
        if (loanApply.getLoanAmount() != null && loanApply.getApplyAmount() != null) {
            if (loanApply.getLoanAmount().compareTo(loanApply.getApplyAmount()) > 0) {
                return R.error(201, "放款金额不能大于申请金额");
            }
        }

        LoanApplyDO apply = loanApplyService.get(loanApply.getId());
        if ("5".equals(apply.getStatus())) {
            return R.error(201, "该笔已还清，暂不可生成账单");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", apply.getUserId());
        List<RepayLogDO> repayLog = repayLogService.list(map);
        for (int i = 0; i < repayLog.size(); i++) {
            RepayLogDO repay = repayLog.get(i);
            repayLogService.remove(repay.getId());
        }
        LoanApplyLogDO applyLogDO = loanApplyLogService.getLastNewData(map);
        loanApply.setRemark9("固定还款日");
        applyLogDO.setAlreadyRepaymentAmt(new BigDecimal(0.00));
        loanApply.setRemark2("0");
        BigDecimal big = new BigDecimal(0);
        if (loanApply.getLoanAmount() == null) {
            return R.error(201, "放款金额不能为空");
        }
        if (loanApply.getLoanAmount().compareTo(big) < 0) {
            return R.error(201, "放款金额不能为空");
        }
        if (StringUtils.isEmpty(loanApply.getRemark1())) {
            return R.error(201, "请先填写利息金额");
        } else {
            if (new BigDecimal(loanApply.getRemark1()).compareTo(big) < 0) {
                return R.error(201, "请先填写利息金额");
            }
        }

        if (StringUtils.isEmpty(loanApply.getLoanPeriod())) {
            return R.error(201, "还款天数不能为空");
        }

        if (StringUtils.isEmpty(loanApply.getLoanRate())) {
            return R.error(201, "还款利息不能为空");
        }

        if (StringUtils.isEmpty(apply.getRemark5())) {
            return R.error(201, "此笔还未放款,无法生成账单");
        }
        BigDecimal totalRepaymentAmt = loanApply.getLoanAmount().add(new BigDecimal(loanApply.getRemark1())).setScale(2, BigDecimal.ROUND_DOWN);
        if (StringUtils.isEmpty(loanApply.getRemark2())) {
            loanApply.setRemark2("0");
        }
        BigDecimal remainRepaymentAmt = totalRepaymentAmt.subtract(new BigDecimal(loanApply.getRemark2())).setScale(2, BigDecimal.ROUND_DOWN);
        applyLogDO.setTotalRepaymentAmt(totalRepaymentAmt);
        applyLogDO.setRemainRepaymentAmt(remainRepaymentAmt);
        applyLogDO.setInterest(new BigDecimal(loanApply.getRemark1()));
        loanApply.setRemark3(remainRepaymentAmt.toString());
        //Calendar c =  Calendar.getInstance();
        //c.add(Calendar.DAY_OF_MONTH,Integer.parseInt(loanApply.getLoanPeriod()));
        //applyLogDO.setRepaymentTime(c.getTime());

        //开始设置还款方式=000000000000000000000=============================
        //月
        int month = Integer.parseInt(loanApply.getLoanPeriod()) / 30;
        //天
        SimpleDateFormat objSDF = new SimpleDateFormat("yyyy-MM-dd");
        int day = DateUtils.daysBetween(objSDF.parse(apply.getRemark5()), DateUtils.get15Day());
        //利率
        String yearRateStr = "0.01";
        if (loanApply.getLoanRate().contains("%")) {
            yearRateStr = loanApply.getLoanRate().replace("%", "");
            double a = Double.parseDouble(yearRateStr);
            a = a / 100;
            yearRateStr = String.valueOf(a);
        } else {
            yearRateStr = loanApply.getLoanRate();
            double a = Double.parseDouble(yearRateStr);
            a = a / 100;
            yearRateStr = String.valueOf(a);
        }
        double yearRate = Double.parseDouble(yearRateStr); // 月利率
        //每天利息
        BigDecimal everyDayLiXi = new BigDecimal(0);
        everyDayLiXi = loanApply.getLoanAmount().multiply(new BigDecimal(yearRate));
        everyDayLiXi = everyDayLiXi.divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN);
        //每天本金
        BigDecimal everyDayBen = new BigDecimal(0);
        everyDayBen = loanApply.getLoanAmount().divide(new BigDecimal(month), 2, BigDecimal.ROUND_DOWN);
        everyDayBen = everyDayBen.divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN);
        //每月还款金额
        BigDecimal needAmt = loanApply.getLoanAmount().add(new BigDecimal(loanApply.getRemark1()));
        needAmt = needAmt.divide(new BigDecimal(month), 2, BigDecimal.ROUND_DOWN);
        BigDecimal needAmt11 = new BigDecimal(0);
        for (int i = 1; i <= month; i++) {
            RepayLogDO repay = new RepayLogDO();
            if (i == 1) {
                BigDecimal needBen = everyDayBen.multiply(new BigDecimal(day));
                //BigDecimal needLixi=everyDayLiXi.multiply(new BigDecimal(day));
                BigDecimal needLixi = new BigDecimal(loanApply.getRemark1()).divide(new BigDecimal(loanApply.getLoanPeriod()), 2, BigDecimal.ROUND_DOWN);
                needLixi = needLixi.multiply(new BigDecimal(day));
                needAmt11 = needBen.add(needLixi).setScale(0, BigDecimal.ROUND_DOWN);
                repay.setAmt(needAmt11);
                repay.setRemark1(needBen.toString());
                repay.setRemark2(needLixi.toString());
                repay.setRemark3(String.valueOf(day));
            } else if (i == month) {
                BigDecimal needAmt22 = needAmt.multiply(new BigDecimal(2));
                needAmt22 = needAmt22.subtract(needAmt11);
                repay.setAmt(needAmt22);
            } else {
                repay.setAmt(needAmt);
            }
            repay.setCreateTime(new Date());
            repay.setPeriod(Long.valueOf(i));
            try {
                //repay.setRepayTime(objSDF.parse(DateUtils.getDateData(i,new Date())));
                String time = DateUtils.getDateData(i, objSDF.parse(apply.getRemark5()));
                time = time.substring(0, 7);
                time = time + "-15 00:00:00";
                repay.setRepayTime(objSDF.parse(time));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            repay.setUserId(apply.getUserId());
            repay.setStatus("0");
            repay.setUserName(apply.getRealName());
            repayLogService.save(repay);
        }
        //========00000000000000000000000000000=================================
        loanApplyService.update(loanApply);
        loanApplyLogService.update(applyLogDO);
        return R.ok();
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:loanApply:add")
    public R save(LoanApplyDO loanApply) {
        if (loanApplyService.save(loanApply) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:loanApply:edit")
    public R update(LoanApplyDO loanApply) {
        if (loanApply.getLoanAmount() != null && loanApply.getApplyAmount() != null) {
            if (loanApply.getLoanAmount().compareTo(loanApply.getApplyAmount()) > 0) {
                return R.error(201, "放款金额不能大于申请金额");
            }
        }
        if (loanApply.getApplyAmount() == null) {
            loanApply.setApplyAmount(new BigDecimal(0));
        }
        LoanApplyDO apply = loanApplyService.get(loanApply.getId());
        if ("3".equals(apply.getStatus()) || "5".equals(apply.getStatus())) {
            return R.error(201, "该笔正在待还状态，不可修改");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", apply.getUserId());
        LoanApplyLogDO applyLogDO = loanApplyLogService.getLastNewData(map);
        if (applyLogDO == null) {
            return R.error(201, "用户还未上传合同");
        }
        if (StringUtils.isNotEmpty(loanApply.getRemark1())) {
            if (StringUtils.isEmpty(loanApply.getRemark9())) {
                return R.error(201, "请选择还款方式");
            }
        }

        if (StringUtils.isNotEmpty(loanApply.getRemark2())) {
            applyLogDO.setAlreadyRepaymentAmt(new BigDecimal(loanApply.getRemark2()));
        } else {
            applyLogDO.setAlreadyRepaymentAmt(new BigDecimal(0.00));
        }
        loanApplyService.update(loanApply);
        loanApplyLogService.update(applyLogDO);

        //--操作日志--开始--
        String shopId = getUser().getEmail();
        String adminName = getUser().getName();
        String Module = "申请认证";
        String detail = "";
        if ("0".equals(apply.getStatus())) {
            detail = "填写申请金额,【" + loanApply.getRealName() + "】【" + loanApply.getApplyAmount() + "】";
        } else if ("2".equals(apply.getStatus())) {
            detail = "填写放款金额,【" + loanApply.getRealName() + "】【" + loanApply.getLoanAmount() + "】,利息【" + loanApply.getRemark1() + "】,还款方式【" + loanApply.getRemark9() + "】";
        } else if ("4".equals(apply.getStatus())) {
            detail = "填写已还金额,【" + loanApply.getRealName() + "】【" + loanApply.getRemark2() + "】";
        }
        loanAdminLogService.saveLog(shopId, adminName, Module, detail);
        //--操作日志--结束--

        return R.ok();
    }

    //借款状态 0 申请中, 1 待放款,2，放款中，3已放款  4，还款中，5已还清  6拒绝
    @ResponseBody
    @RequestMapping("/pass")
    @RequiresPermissions("system:loanApply:pass")
    public R pass(LoanApplyDO loanApply) {
        if (loanApply == null) {
            return R.error(201, "数据不存在");
        }
        loanApply = loanApplyService.get(loanApply.getId());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", loanApply.getUserId());
        LoanApplyLogDO applyLogDO = loanApplyLogService.getLastNewData(map);
        if (applyLogDO == null) {
            return R.error(201, "用户还未上传合同");
        }
        if (!"2".equals(loanApply.getUserInfoAuth())) {
            return R.error(201, "用户基础信息未完善");
        }
        if (!"2".equals(loanApply.getContactAuth())) {
            return R.error(201, "用户联系人信息未完善");
        }
        if (!"2".equals(loanApply.getBankAuth())) {
            return R.error(201, "银行卡实名未认证");
        }
        if (!"2".equals(loanApply.getFaceAuth())) {
            return R.error(201, "人脸识别未认证");
        }
        if (!"2".equals(loanApply.getCreditAuth())) {
            return R.error(201, "征信还未授权认证");
        }
        if (loanApply.getLoanProductId() == null || loanApply.getLoanProductName() == null) {
            return R.error(201, "未关联借贷产品");
        }
        LoanUserDO userDO = loanUserService.get(loanApply.getUserId());

        if ("0".equals(loanApply.getStatus())) {
            loanApply.setStatus("1");
            BigDecimal big = new BigDecimal(1);
            if (loanApply.getApplyAmount() == null) {
                return R.error(201, "请先审批申请金额");
            }
            if (loanApply.getApplyAmount().compareTo(big) < 0) {
                return R.error(201, "请先审批申请金额");
            }
            userDO.setStatus("1");
            applyLogDO.setStatus("1");
            applyLogDO.setApplyAmt(loanApply.getApplyAmount());
            applyLogDO.setRealName(userDO.getRealName());
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "审批通过申请【" + loanApply.getRealName() + "】【申请中-->待放款】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("1".equals(loanApply.getStatus())) {
            loanApply.setStatus("2");
            userDO.setStatus("2");
            applyLogDO.setStatus("2");
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "审批通过【" + loanApply.getRealName() + "】【待放款-->放款中】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("2".equals(loanApply.getStatus())) {
            loanApply.setStatus("3");
            userDO.setStatus("3");
            applyLogDO.setStatus("3");
            applyLogDO.setLoanAmt(loanApply.getLoanAmount());
            applyLogDO.setLoanTime(new Date());
            BigDecimal big = new BigDecimal(0);
            if (loanApply.getLoanAmount() == null) {
                return R.error(201, "请先审批放款金额");
            }
            if (loanApply.getLoanAmount().compareTo(big) < 0) {
                return R.error(201, "请先审批放款金额");
            }

            if (StringUtils.isEmpty(loanApply.getRemark1())) {
                return R.error(201, "请先填写利息金额");
            } else {
                if (new BigDecimal(loanApply.getRemark1()).compareTo(big) < 0) {
                    return R.error(201, "请先填写利息金额");
                }
            }

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            BigDecimal totalRepaymentAmt = loanApply.getLoanAmount().add(new BigDecimal(loanApply.getRemark1())).setScale(2, BigDecimal.ROUND_DOWN);
            if (StringUtils.isEmpty(loanApply.getRemark2())) {
                loanApply.setRemark2("0");
            }
            BigDecimal remainRepaymentAmt = totalRepaymentAmt.subtract(new BigDecimal(loanApply.getRemark2())).setScale(2, BigDecimal.ROUND_DOWN);
            applyLogDO.setTotalRepaymentAmt(totalRepaymentAmt);
            applyLogDO.setRemainRepaymentAmt(remainRepaymentAmt);
            applyLogDO.setInterest(new BigDecimal(loanApply.getRemark1()));

            loanApply.setRemark3(remainRepaymentAmt.toString());
            loanApply.setRemark5(sdf.format(date));//放款时间

            Calendar c = Calendar.getInstance();
            c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(loanApply.getLoanPeriod()));
            String mDateTime = sdf.format(c.getTime());
            String resultTime = mDateTime.substring(0, 10);
            loanApply.setRemark4(resultTime);//还款时间
            applyLogDO.setRepaymentTime(c.getTime());
            if (StringUtils.isEmpty(loanApply.getRemark9())) {
                applyLogDO.setRemark1("等额本息");//还款方式
            } else {
                applyLogDO.setRemark1(loanApply.getRemark9());//还款方式
            }
            //开始设置还款方式=000000000000000000000=============================
            if (StringUtils.isNotEmpty(loanApply.getRemark9())) {
                if ("先息后本".equals(loanApply.getRemark9())) {
                    int month = Integer.parseInt(loanApply.getLoanPeriod()) / 30;
                    SimpleDateFormat objSDF = new SimpleDateFormat("yyyy-MM-dd");
                    BigDecimal everyLixi = new BigDecimal(0);
                    everyLixi = new BigDecimal(loanApply.getRemark1()).divide(new BigDecimal(month), 2, BigDecimal.ROUND_DOWN);
                    for (int i = 1; i <= month; i++) {
                        RepayLogDO repay = new RepayLogDO();
                        if (i == month) {
                            repay.setAmt(everyLixi.add(loanApply.getLoanAmount()));
                        } else {
                            repay.setAmt(everyLixi);
                        }
                        repay.setCreateTime(new Date());
                        repay.setPeriod(Long.valueOf(i));
                        try {
                            repay.setRepayTime(objSDF.parse(DateUtils.getDateData(i, new Date())));
						/*String time=DateUtils.getDateData(i,objSDF.parse(loanApply.getRemark5()));
						time=time.substring(0, 7);
						time=time+"-15 00:00:00";
						repay.setRepayTime(objSDF.parse(time));*/
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        repay.setUserId(loanApply.getUserId());
                        repay.setStatus("0");
                        repay.setUserName(loanApply.getRealName());
                        repayLogService.save(repay);
                    }
                } else if ("固定还款日".equals(loanApply.getRemark9())) {
                    //----------------------------------------------
                    //月
                    int month = Integer.parseInt(loanApply.getLoanPeriod()) / 30;
                    //天
                    int day = DateUtils.daysBetween(new Date(), DateUtils.get15Day());
                    //利率
                    String yearRateStr = "0.01";
                    if (loanApply.getLoanRate().contains("%")) {
                        yearRateStr = loanApply.getLoanRate().replace("%", "");
                        double a = Double.parseDouble(yearRateStr);
                        a = a / 100;
                        yearRateStr = String.valueOf(a);
                    } else {
                        yearRateStr = loanApply.getLoanRate();
                        double a = Double.parseDouble(yearRateStr);
                        a = a / 100;
                        yearRateStr = String.valueOf(a);
                    }
                    double yearRate = Double.parseDouble(yearRateStr); // 月利率
                    SimpleDateFormat objSDF = new SimpleDateFormat("yyyy-MM-dd");
                    //每天利息
                    BigDecimal everyDayLiXi = new BigDecimal(0);
                    everyDayLiXi = loanApply.getLoanAmount().multiply(new BigDecimal(yearRate));
                    everyDayLiXi = everyDayLiXi.divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN);
                    //每天本金
                    BigDecimal everyDayBen = new BigDecimal(0);
                    everyDayBen = loanApply.getLoanAmount().divide(new BigDecimal(month), 2, BigDecimal.ROUND_DOWN);
                    everyDayBen = everyDayBen.divide(new BigDecimal(30), 2, BigDecimal.ROUND_DOWN);
                    //每月还款金额
                    BigDecimal needAmt = loanApply.getLoanAmount().add(new BigDecimal(loanApply.getRemark1()));
                    needAmt = needAmt.divide(new BigDecimal(month), 2, BigDecimal.ROUND_DOWN);
                    BigDecimal needAmt11 = new BigDecimal(0);
                    for (int i = 1; i <= month; i++) {
                        RepayLogDO repay = new RepayLogDO();
                        if (i == 1) {
                            BigDecimal needBen = everyDayBen.multiply(new BigDecimal(day));
                            //BigDecimal needLixi=everyDayLiXi.multiply(new BigDecimal(day));
                            BigDecimal needLixi = new BigDecimal(loanApply.getRemark1()).divide(new BigDecimal(loanApply.getLoanPeriod()), 2, BigDecimal.ROUND_DOWN);
                            needLixi = needLixi.multiply(new BigDecimal(day));
                            needAmt11 = needBen.add(needLixi).setScale(0, BigDecimal.ROUND_DOWN);
                            repay.setAmt(needAmt11);
                        } else if (i == month) {
                            BigDecimal needAmt22 = needAmt.multiply(new BigDecimal(2));
                            needAmt22 = needAmt22.subtract(needAmt11);
                            repay.setAmt(needAmt22);
                        } else {
                            repay.setAmt(needAmt);
                        }
                        repay.setCreateTime(new Date());
                        repay.setPeriod(Long.valueOf(i));
                        try {
                            //repay.setRepayTime(objSDF.parse(DateUtils.getDateData(i,new Date())));
                            String time = DateUtils.getDateData(i, objSDF.parse(loanApply.getRemark5()));
                            time = time.substring(0, 7);
                            time = time + "-15 00:00:00";
                            repay.setRepayTime(objSDF.parse(time));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        repay.setUserId(loanApply.getUserId());
                        repay.setStatus("0");
                        repay.setUserName(loanApply.getRealName());
                        repayLogService.save(repay);
                    }
                    //----------------------------------------------
                }
            }
            //========00000000000000000000000000000=================================

            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "审批通过【" + loanApply.getRealName() + "】【放款中-->已放款】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("3".equals(loanApply.getStatus())) {
            loanApply.setStatus("4");
            userDO.setStatus("4");
            applyLogDO.setStatus("4");
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "审批通过【" + loanApply.getRealName() + "】【已放款-->还款中】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("4".equals(loanApply.getStatus())) {
            BigDecimal lixi = null;
            BigDecimal yihuan = null;
            if (StringUtils.isEmpty(loanApply.getRemark1())) {//利息
                lixi = new BigDecimal(0);
            } else {
                lixi = new BigDecimal(loanApply.getRemark1());
            }

            if (StringUtils.isEmpty(loanApply.getRemark2())) {//已还
                yihuan = new BigDecimal(0);
            } else {
                yihuan = new BigDecimal(loanApply.getRemark2());
            }
            BigDecimal totalLoan = loanApply.getLoanAmount().add(lixi).setScale(2, BigDecimal.ROUND_DOWN);
            if (totalLoan.compareTo(yihuan) > 0) {
                return R.error(202, "改用户还未还清当前借款");
            }
            loanApply.setStatus("5");
            userDO.setStatus("5");
            applyLogDO.setStatus("5");
            applyLogDO.setAlreadyRepaymentAmt(new BigDecimal(loanApply.getRemark2()));
            loanApply.setApplyAmount(null);
            loanApply.setLoanAmount(null);
            loanApply.setRemark1(null);
            loanApply.setRemark2(null);
            loanApply.setRemark9(null);
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "审批通过【" + loanApply.getRealName() + "】已还清,暂无欠款";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("5".equals(loanApply.getStatus())) {
            return R.error(202, "不存在需申请借款申请记录");
        } else {
            loanApply.setStatus("1");
            userDO.setStatus("1");
        }
        loanUserService.update(userDO);
        loanApplyService.update(loanApply);
        loanApplyLogService.update(applyLogDO);
        return R.ok();
    }

    //通过人脸识别
    @ResponseBody
    @RequestMapping("/passFace")
    @RequiresPermissions("system:loanApply:pass")
    public R passFace(LoanApplyDO loanApply) {
        if (loanApply == null) {
            return R.error(201, "数据不存在");
        }
        loanApply = loanApplyService.get(loanApply.getId());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", loanApply.getUserId());
        List<LoanFaceDO> loanFaceDOs = loanFaceService.list(map);
        if (loanFaceDOs != null && loanFaceDOs.size() > 0) {
            LoanFaceDO faceDO = loanFaceDOs.get(0);
            faceDO.setStatus("2");
            loanFaceService.update(faceDO);
        } else {
            return R.error(201, "还未进行人脸认证");
        }
        loanApply.setFaceAuth("2");
        loanApplyService.update(loanApply);
        return R.ok();
    }


    //驳回人脸识别
    @ResponseBody
    @RequestMapping("/noPassFace")
    @RequiresPermissions("system:loanApply:pass")
    public R noPassFace(LoanApplyDO loanApply) {
        if (loanApply == null) {
            return R.error(201, "数据不存在");
        }
        loanApply = loanApplyService.get(loanApply.getId());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", loanApply.getUserId());
        List<LoanFaceDO> loanFaceDOs = loanFaceService.list(map);
        if (loanFaceDOs != null && loanFaceDOs.size() > 0) {
            LoanFaceDO faceDO = loanFaceDOs.get(0);
            faceDO.setStatus("0");
            loanFaceService.update(faceDO);
        } else {
            return R.error(201, "还未进行人脸认证");
        }
        loanApply.setFaceAuth("0");
        loanApplyService.update(loanApply);
        return R.ok();
    }


    //通过运营商认证
    @ResponseBody
    @RequestMapping("/passPhone")
    @RequiresPermissions("system:loanApply:pass")
    public R passPhone(LoanApplyDO loanApply) {
        if (loanApply == null) {
            return R.error(201, "数据不存在");
        }
        loanApply = loanApplyService.get(loanApply.getId());
        loanApply.setCreditAuth("2");
        loanApplyService.update(loanApply);
        return R.ok();
    }

    @ResponseBody
    @RequestMapping("/noPass")
    @RequiresPermissions("system:loanApply:noPass")
    public R noPass(LoanApplyDO loanApply) {
        loanApply = loanApplyService.get(loanApply.getId());
        LoanUserDO userDO = loanUserService.get(loanApply.getUserId());

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", loanApply.getUserId());
        LoanApplyLogDO applyLogDO = loanApplyLogService.getLastNewData(map);
        if (applyLogDO == null) {
            return R.error(201, "用户还未上传合同");
        }

        if ("0".equals(loanApply.getStatus())) {
            loanApply.setStatus("0");
            userDO.setStatus("0");
            applyLogDO.setStatus("0");
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "驳回操作【" + loanApply.getRealName() + "】【-->申请中】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("1".equals(loanApply.getStatus())) {
            loanApply.setStatus("0");
            userDO.setStatus("0");
            applyLogDO.setStatus("0");
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "驳回操作【" + loanApply.getRealName() + "】【-->申请中】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("2".equals(loanApply.getStatus())) {
            loanApply.setStatus("1");
            userDO.setStatus("1");
            applyLogDO.setStatus("1");
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "驳回操作【" + loanApply.getRealName() + "】【-->待放款】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("3".equals(loanApply.getStatus())) {
            loanApply.setStatus("2");
            userDO.setStatus("2");
            applyLogDO.setStatus("2");
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "驳回操作【" + loanApply.getRealName() + "】【-->放款中】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("4".equals(loanApply.getStatus())) {
            loanApply.setStatus("3");
            userDO.setStatus("3");
            applyLogDO.setStatus("3");
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "驳回操作【" + loanApply.getRealName() + "】【-->已放款】";
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } else if ("5".equals(loanApply.getStatus())) {
            return R.error(202, "不存在需驳回借款申请记录");
        } else {
            loanApply.setStatus("0");
            userDO.setStatus("0");
            applyLogDO.setStatus("0");
        }
        loanUserService.update(userDO);
        loanApplyService.update(loanApply);
        loanApplyLogService.update(applyLogDO);
        return R.ok();
    }

    /**
     * 清空
     */
    @PostMapping("/clear")
    @ResponseBody
    @RequiresPermissions("system:loanApply:remove")
    public R clear(LoanApplyDO loanApply) {
        try {
            //后期这边要加入事务
            loanApplyService.updateHasemptyById(loanApply.getId());
            loanApplyLogService.updateHasemptyByUserId(loanApply.getUserId());
            loanContactService.updateHasemptyByUserId(loanApply.getUserId());
            loanFaceService.updateHasemptyByUserId(loanApply.getUserId());
            loanFaceLogService.updateHasemptyByUserId(loanApply.getUserId());
            loanFileService.updateHasemptyByUserId(loanApply.getUserId());
            loanBankService.updateHasemptyByUserId(loanApply.getUserId());
            repayLogService.updateHasemptyByUserId(loanApply.getUserId());
            LoanUserDO userDO = loanUserService.get(loanApply.getUserId());
            if (userDO != null) {
                userDO.setStatus("7");//代表借贷信息已清空
                loanUserService.update(userDO);
            }
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "";
            if (userDO != null) {
                detail = "拒绝了【" + userDO.getRealName() + "ID:" + loanApply.getUserId() + "】的申请";
            } else {
                detail = "拒绝了【ID:" + loanApply.getUserId() + "】的申请";
            }
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
        } catch (Exception e) {
            return R.error();
        }
        return R.ok();
    }

    /**
     * 后台拒绝
     * 借款状态 0 申请中, 1 待放款,2，放款中，3已放款  4，还款中，5已还清  6,拒绝
     */
    @PostMapping("/refuse")
    @ResponseBody
    @RequiresPermissions("system:loanApply:refuse")
    public R refuse(LoanApplyDO loanApply) {
        loanApply = loanApplyService.get(loanApply.getId());
        loanApply.setStatus("6");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", loanApply.getUserId());
        LoanApplyLogDO applyLogDO = loanApplyLogService.getLastNewData(map);
        applyLogDO.setStatus("6");
        if (loanApplyService.refuse(loanApply.getId()) > 0) {
            loanApplyService.update(loanApply);
            LoanUserDO userDO = loanUserService.get(loanApply.getUserId());
            if (userDO != null) {
                userDO.setStatus("6");
                loanUserService.update(userDO);
            }
            loanApplyLogService.update(applyLogDO);
            //--操作日志--开始--
            String shopId = getUser().getEmail();
            String adminName = getUser().getName();
            String Module = "申请认证";
            String detail = "";
            if (userDO != null) {
                detail = "拒绝了【" + userDO.getRealName() + "ID:" + loanApply.getUserId() + "】的申请";
            } else {
                detail = "拒绝了【ID:" + loanApply.getUserId() + "】的申请";
            }
            loanAdminLogService.saveLog(shopId, adminName, Module, detail);
            //--操作日志--结束--
            return R.ok();
        }
        return R.error();
    }

    /**
     * 前端拒绝
     * 总后台点“拒绝”后门店看的借款状态显示“拒绝”，门店点再次点击“拒绝” 客户所注册的手机将短信接收到拒绝
     */
    @PostMapping("/preRefuse")
    @ResponseBody
    @RequiresPermissions("system:loanApply:refuse")
    public R preRefuse(LoanApplyDO loanApply) {
        try {
            LoanApplyDO loanApplyDONew = new LoanApplyDO();
            loanApplyDONew.setId(loanApply.getId());
            if (loanApplyService.update(loanApplyDONew) > 0) {
                Map<String, Object> params = new HashMap<>();
                params.put("code", "被拒绝啦");
                //new SmsTools().sendMessage(loanApply.getRemark6(), JSON.toJSONString(params),"SMS_143660251");
                return R.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:loanApply:remove")
    public R remove(Long id) {
        if (loanApplyService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:loanApply:batchRemove")
    public R remove(@RequestParam("ids[]") Long[] ids) {
        loanApplyService.batchRemove(ids);
        return R.ok();
    }

}
